package com.example.zselasticsearchsf.config;


import com.alibaba.fastjson.JSON;
import com.example.zselasticsearchsf.config.es.request.CoreSearchReqDto;
import com.example.zselasticsearchsf.config.es.request.SearchReqDto;
import com.example.zselasticsearchsf.config.es.respons.SearchRepDto;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.core.TimeValue;
import org.elasticsearch.index.query.*;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramInterval;
import org.elasticsearch.search.aggregations.bucket.histogram.Histogram;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static org.elasticsearch.index.query.QueryBuilders.matchQuery;

/**
 * 全文搜索
 *
 * @Author: Steven
 * @Date: 2021/11/3 22:30
 */
@Component
public class SearchUtil {


    @Resource
    private RestHighLevelClient client;

    /**
     * <p>关键词高亮查询</p>
     *
     * @param searchReqDto 搜索请求Bean
     * @return
     */
    public Map<String, Object> highLightMatch(SearchReqDto searchReqDto) {
        //#region 参数初始化
        String keywords;
        Integer pages;
        Integer size;
        String index_name = searchReqDto.getIndex();
        String searchFiled = searchReqDto.getSearchFiled();
        if (index_name.equals("1")) {
            searchFiled = "caseTitle";
            index_name = "case_info_b";
        } else if (index_name.equals("2")) {
            searchFiled = "contextTitle";
            index_name = "law_info_b";
        } else if (index_name.equals("3")) {
            searchFiled = "context";
            index_name = "case_info_b";
        } else if (index_name.equals("4")) {
            searchFiled = "context";
            index_name = "law_info_b";
        }

        if (searchReqDto.getKeywords() == null) {
            keywords = "";
        } else {
            keywords = searchReqDto.getKeywords();
        }
        if (searchReqDto.getPage() == null) {
            pages = 1;
        } else {
            pages = searchReqDto.getPage();
        }
        if (searchReqDto.getSize() == null) {
            size = 10;
        } else {
            size = searchReqDto.getSize();
        }
        //#endregion

        // 构建QueryBuilder对象指定查询方式
//        QueryBuilder queryBuilder = matchQuery(searchFiled, keywords);
        MatchPhraseQueryBuilder queryBuilder = QueryBuilders
                .matchPhraseQuery(searchFiled, keywords);

        // 构建SearchRequest请求对象,指定索引库
        SearchRequest searchRequest = new SearchRequest(index_name);
        // 构建SearchSourceBuilder查询对象
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        // 将QueryBuilder对象设置到SearchSourceBuilder中
        sourceBuilder.query(queryBuilder);
        /**
         *  from：当前页起始索引  从0开始 int from = (pageNum - 1) * size;
         *  size：每页显示多少条
         */
        sourceBuilder.size(size);
        sourceBuilder.from((pages - 1) * size);
        sourceBuilder.trackTotalHits(true);
        /**
         * 通过sort方法指定排序规则
         * 第一个参数：排序字段
         * 第二个参数：升序还是降序(可以不填写，默认升序)
         */
        if (searchReqDto.getSortFiled() != null) {
            if (searchReqDto.getSortOrder() == -1) {
                sourceBuilder.sort(searchReqDto.getSortFiled(), SortOrder.DESC);
            } else {
                sourceBuilder.sort(searchReqDto.getSortFiled(), SortOrder.ASC);
            }
        }

        // 构建HighlightBuilder高亮对象
        HighlightBuilder highlightBuilder = new HighlightBuilder();

        // 设置要高亮的字段
        highlightBuilder.field(searchFiled);

        // 设置高亮样式
//        highlightBuilder.preTags("<font color='pink';font-weight: 700' >");
        highlightBuilder.preTags("<span style='color:red;'>");
        highlightBuilder.postTags("</span>");
        // 6.将高亮对象highlightBuilder设置到sourceBuilder中
        sourceBuilder.highlighter(highlightBuilder);
        // 7.将SearchSourceBuilder查询对象封装到请求对象SearchRequest中
        searchRequest.source(sourceBuilder);
        SearchResponse searchResponse = null;
        List<SearchRepDto> searchResultList = new ArrayList<>();
        Map<String, Object> resMap = new HashMap<>();
        SearchHit[] hits = null;
        Long total = null;
        try {
            // 调用方法进行数据通信
            searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
            // 解析输出结果
            hits = searchResponse.getHits().getHits();
            total = searchResponse.getHits().getTotalHits().value;

            for (SearchHit hit : hits) {
                String id = hit.getId();
                String sourceAsString = hit.getSourceAsString();
                SearchRepDto searchResult = new SearchRepDto();

                System.out.println("结果：" + sourceAsString);
                // 解析高亮结果
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                HighlightField highlightField = highlightFields.get(searchFiled);
                Text[] fragments = highlightField.getFragments();

                for (Text fragment : fragments) {
                    if (searchReqDto.getIndex().equals("1") || searchReqDto.getIndex().equals("2")) {
                        searchResult.setHighlightField(fragment.toString());
                    } else if (searchReqDto.getIndex().equals("3")) {
                        searchResult.setHighlightField(JSON.parseObject(sourceAsString).getString("caseTitle"));
                    } else if (searchReqDto.getIndex().equals("4")) {
                        searchResult.setHighlightField(JSON.parseObject(sourceAsString).getString("contextTitle"));
                    }
                    searchResult.setId(id);
                    searchResult.setType(searchReqDto.getIndex());
                    searchResult.setSourceAsString(JSON.parseObject(sourceAsString));

                    searchResultList.add(searchResult);
                    resMap.put("searchResultList", searchResultList);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        resMap.put("total", total);
        System.out.println("=================="+total);
        return resMap;
    }

    /**
     * <p>高级客户揣 精确查询</p>
     *
     * @param index_name  索引名称 不能出现大写！！！
     * @param searchFiled 搜索的字段名
     * @param searchValue 搜索的值
     * @return
     * @throws IOException
     */
    public SearchRepDto termQuery(String index_name, String searchFiled, String searchValue) throws IOException {

        if (index_name.equals("1") || index_name.equals("3")) {
            index_name = "case_info_b";
        } else if (index_name.equals("2") || index_name.equals("4")) {
            index_name = "law_info_b";
        }

        SearchRequest searchRequest = new SearchRequest(index_name);
        //构建搜索条件
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery(searchFiled, searchValue);
        sourceBuilder.query(termQueryBuilder);
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        searchRequest.source(sourceBuilder);
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        // 9.解析输出结果
        SearchHit[] hits = searchResponse.getHits().getHits();
        SearchRepDto searchResult = new SearchRepDto();

        for (SearchHit hit : hits) {
            String sourceAsString = hit.getSourceAsString();
            searchResult.setSourceAsString(JSON.parseObject(sourceAsString));
        }
        return searchResult;
    }

    /**
     * 时间段分组
     *
     * @return
     * @throws IOException
     */
    public Map<String, Object> yearRangeQuery() throws IOException {

        SearchRequest searchRequest = new SearchRequest();
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.matchAllQuery());
        DateHistogramAggregationBuilder dateHistogramAggregationBuilder = AggregationBuilders.dateHistogram("group_by_time")
                .field("publishDate")
                .calendarInterval(DateHistogramInterval.YEAR)
                .format("yyyy");
        searchSourceBuilder.aggregation(dateHistogramAggregationBuilder);
        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        Aggregations aggregations = searchResponse.getAggregations();

        Histogram histogram = aggregations.get("group_by_time");

        List<? extends Histogram.Bucket> buckets = histogram.getBuckets();
        List<Map<String, Object>> list = new ArrayList<>();
        long total = 0;
        for (Histogram.Bucket bucket : buckets) {
            Map<String, Object> timeResMap = new HashMap<>();
            String key = bucket.getKeyAsString();
            System.out.println("key:" + key);
            long docCount = bucket.getDocCount();
            System.out.println("docCount:" + docCount);
            timeResMap.put("year", key);
            timeResMap.put("num", docCount);
            total += docCount;
            list.add(timeResMap);
        }
        Map<String, Object> resMap = new HashMap<>();
        resMap.put("total", total);
        resMap.put("resList", list);
        return resMap;
    }

    /**
     * 地域分组
     *
     * @return
     * @throws IOException
     */

    public Map<String, Object> areaRangeQuery() throws IOException {

        SearchRequest searchRequest = new SearchRequest();
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.matchAllQuery());
        //       地域 分组统计
        TermsAggregationBuilder termsAggregationBuilder = AggregationBuilders.terms("group_by_area").field("distName");
        searchSourceBuilder.aggregation(termsAggregationBuilder);
        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        Aggregations aggregations = searchResponse.getAggregations();

        Terms histogram = aggregations.get("group_by_area");


        List<? extends Terms.Bucket> buckets = histogram.getBuckets();
        List<Map<String, Object>> list = new ArrayList<>();
        long total = 0;
        for (Terms.Bucket bucket : buckets) {
            Map<String, Object> timeResMap = new HashMap<>();
            String key = bucket.getKeyAsString();
            System.out.println("key:" + key);
            long docCount = bucket.getDocCount();
            System.out.println("docCount:" + docCount);
            timeResMap.put("city", key);
            timeResMap.put("num", docCount);
            total += docCount;
            list.add(timeResMap);
        }
        Map<String, Object> resMap = new HashMap<>();
        resMap.put("total", total);
        resMap.put("resList", list);
        return resMap;
    }

    /**
     * 类型分组
     *
     * @return
     * @throws IOException
     */

    public Map<String, Object> typeRangeQuery() throws IOException {

        SearchRequest searchRequest = new SearchRequest();
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.matchAllQuery());
        //       类型 分组统计
        TermsAggregationBuilder termsAggregationBuilder = AggregationBuilders.terms("group_by_type").field("typeName");
        searchSourceBuilder.aggregation(termsAggregationBuilder);
        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        Aggregations aggregations = searchResponse.getAggregations();

        Terms histogram = aggregations.get("group_by_type");


        List<? extends Terms.Bucket> buckets = histogram.getBuckets();
        List<Map<String, Object>> list = new ArrayList<>();
        long total = 0;
        for (Terms.Bucket bucket : buckets) {
            Map<String, Object> timeResMap = new HashMap<>();
            String key = bucket.getKeyAsString();
            System.out.println("key:" + key);
            long docCount = bucket.getDocCount();
            System.out.println("docCount:" + docCount);
            timeResMap.put("type", key);
            timeResMap.put("num", docCount);
            total += docCount;
            list.add(timeResMap);
        }
        Map<String, Object> resMap = new HashMap<>();
        resMap.put("total", total);
        resMap.put("resList", list);
        return resMap;
    }

    /**
     * 机构分组
     *
     * @return
     * @throws IOException
     */

    public Map<String, Object> mechanismRangeQuery() throws IOException {

        SearchRequest searchRequest = new SearchRequest();
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.matchAllQuery());
        //       地域 分组统计
        TermsAggregationBuilder termsAggregationBuilder = AggregationBuilders.terms("group_by_mechanism").field("uploadDeptName");
        searchSourceBuilder.aggregation(termsAggregationBuilder);
        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        Aggregations aggregations = searchResponse.getAggregations();

        Terms histogram = aggregations.get("group_by_mechanism");


        List<? extends Terms.Bucket> buckets = histogram.getBuckets();
        List<Map<String, Object>> list = new ArrayList<>();
        long total = 0;
        for (Terms.Bucket bucket : buckets) {
            Map<String, Object> timeResMap = new HashMap<>();
            String key = bucket.getKeyAsString();
            System.out.println("key:" + key);
            long docCount = bucket.getDocCount();
            System.out.println("docCount:" + docCount);
            timeResMap.put("mechanism", key);
            timeResMap.put("num", docCount);
            total += docCount;
            list.add(timeResMap);
        }
        Map<String, Object> resMap = new HashMap<>();
        resMap.put("total", total);
        resMap.put("resList", list);
        return resMap;
    }

    /**
     * 分组查询
     * @param rangeString
     * @throws IOException
     */
    public Map<String, Object> searchRangeQuery(String rangeString, Integer rangeType) {

        SearchRequest searchRequest = new SearchRequest();
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();


        //闭区间时间查询
        RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("publishDate").from(rangeString + "-01-01").to(rangeString + "-12-31", true);

        //区域查询
        QueryBuilder matchQuery = null;

        //类型查询

        if (rangeType == 1) {
            sourceBuilder.query(rangeQueryBuilder);
        } else if (rangeType == 2) {
            sourceBuilder.query(matchQuery("distName", rangeString));
        }
        else if (rangeType == 3) {
            sourceBuilder.query( matchQuery("typeName", rangeString));
        }else if (rangeType == 4) {
            sourceBuilder.query( matchQuery("uploadDeptName", rangeString));
        }

        //请求体放入请求头
        searchRequest.source(sourceBuilder);
        Map<String, Object> resMap = new HashMap<>();
        Long total = null;
        try {
            // 调用方法进行数据通信
            SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
            // 解析输出结果
            SearchHit[] hits = searchResponse.getHits().getHits();
            total = searchResponse.getHits().getTotalHits().value;
            List<SearchRepDto> searchResultList = new ArrayList<>();
            System.out.println("总数=========" + total);
            for (SearchHit hit : hits) {
                String id = hit.getId();
                String sourceAsString = hit.getSourceAsString();
                SearchRepDto searchResult = new SearchRepDto();
                System.out.println("结果：" + sourceAsString);

                String index_name = null;
                if (JSON.parseObject(sourceAsString).getString("caseTitle") != null) {
                    searchResult.setHighlightField(JSON.parseObject(sourceAsString).getString("caseTitle"));
                    index_name = "1";
                } else if (JSON.parseObject(sourceAsString).getString("contextTitle") != null) {
                    index_name = "2";
                    searchResult.setHighlightField(JSON.parseObject(sourceAsString).getString("contextTitle"));
                }
                searchResult.setId(id);
                searchResult.setType(index_name);
                searchResult.setSourceAsString(JSON.parseObject(sourceAsString));

                searchResultList.add(searchResult);
                resMap.put("searchResultList", searchResultList);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        resMap.put("total", total);
        return resMap;
    }

    /**
     *高级组和查询
     * must:   AND
     * mustNot: NOT
     * should:: OR
     */
    public Map<String, Object>  BoolSearch(List<CoreSearchReqDto> coreSearchReqDtoList )  {

        System.out.println("coreSearchReqDtoList"+coreSearchReqDtoList);
        SearchRequest searchRequest = new SearchRequest("case_info_b");


        String searchFiled= null;
        QueryBuilder Q_0=null;
        QueryBuilder Q_1=null;
        QueryBuilder Q_2=null;
        QueryBuilder Q_3=null;
        QueryBuilder Q_4=null;
        QueryBuilder Q_5=null;
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();

        for (int i = 0; i <coreSearchReqDtoList.size() ; i++) {

            if(!coreSearchReqDtoList.get(i).getValue().equals("")){

                if(coreSearchReqDtoList.get(i).getKey()==1){
                    searchFiled="caseTitle";
                }else if(coreSearchReqDtoList.get(i).getKey()==2){
                    searchFiled="context";
                }else if(coreSearchReqDtoList.get(i).getKey()==3){
                    searchFiled="distName";
                }else if(coreSearchReqDtoList.get(i).getKey()==4){
                    searchFiled="publishDate";
                }else if(coreSearchReqDtoList.get(i).getKey()==5){
                    searchFiled="uploadDeptName";
                }else if(coreSearchReqDtoList.get(i).getKey()==6){
                    searchFiled="typeName";

                }

                if(i==0){
                    //第一行为基础搜索  区分模糊和精确
                    if(coreSearchReqDtoList.get(i).getAccuracy()==0){
                        Q_0  =QueryBuilders.matchPhraseQuery(searchFiled, coreSearchReqDtoList.get(i).getValue());
                    }else{
                        Q_0=QueryBuilders.termQuery(searchFiled, coreSearchReqDtoList.get(i).getValue());
                    }
                    queryBuilder.must(Q_0);
                }else if(i==1) {
                    if(coreSearchReqDtoList.get(i).getType()==0){//and
                        if(coreSearchReqDtoList.get(i).getAccuracy()==0){// like
                            Q_1=  QueryBuilders.matchPhraseQuery(searchFiled, coreSearchReqDtoList.get(i).getValue());

                        }else if (coreSearchReqDtoList.get(i).getAccuracy()==1){//=
                            Q_1=QueryBuilders.matchPhraseQuery(searchFiled, coreSearchReqDtoList.get(i).getValue());
                        }
                        queryBuilder.should(Q_1);
                    }else {//or
                        queryBuilder.must(Q_1);
                    }
                }else if(i==2) {
                    if(coreSearchReqDtoList.get(i).getType()==0){//and
                        if(coreSearchReqDtoList.get(i).getAccuracy()==0){// like
                            Q_2=  QueryBuilders.matchPhraseQuery(searchFiled, coreSearchReqDtoList.get(i).getValue());
                        }else if (coreSearchReqDtoList.get(i).getAccuracy()==1){//=
                            Q_2=QueryBuilders.matchPhraseQuery(searchFiled, coreSearchReqDtoList.get(i).getValue());
                        }
                        queryBuilder.must(Q_2);
                    }else {//or
                        queryBuilder.should(Q_2);
                    }
                }else if(i==3) {
                    if(coreSearchReqDtoList.get(i).getType()==0){//and
                        if(coreSearchReqDtoList.get(i).getAccuracy()==0){// like
                            Q_3=  QueryBuilders.matchPhraseQuery(searchFiled, coreSearchReqDtoList.get(i).getValue());

                        }else if (coreSearchReqDtoList.get(i).getAccuracy()==1){//=
                            Q_3=QueryBuilders.matchPhraseQuery(searchFiled, coreSearchReqDtoList.get(i).getValue());
                        }
                        queryBuilder.must(Q_3);
                    }else {//or
                        queryBuilder.should(Q_3);
                    }
                }else if(i==4) {
                    if(coreSearchReqDtoList.get(i).getType()==0){//and
                        if(coreSearchReqDtoList.get(i).getAccuracy()==0){// like
                            Q_4=  QueryBuilders.matchPhraseQuery(searchFiled, coreSearchReqDtoList.get(i).getValue());

                        }else if (coreSearchReqDtoList.get(i).getAccuracy()==1){//=
                            Q_4=QueryBuilders.matchPhraseQuery(searchFiled, coreSearchReqDtoList.get(i).getValue());
                        }
                        queryBuilder.must(Q_4);
                    }else {//or
                        queryBuilder.should(Q_4);
                    }
                }else if(i==5) {
                    if(coreSearchReqDtoList.get(i).getType()==0){//and
                        if(coreSearchReqDtoList.get(i).getAccuracy()==0){// like
                            Q_5=  QueryBuilders.matchPhraseQuery(searchFiled, coreSearchReqDtoList.get(i).getValue());

                        }else if (coreSearchReqDtoList.get(i).getAccuracy()==1){//=
                            Q_5=QueryBuilders.matchPhraseQuery(searchFiled, coreSearchReqDtoList.get(i).getValue());
                        }
                        queryBuilder.must(Q_5);
                    }else {//or
                        queryBuilder.should(Q_5);
                    }
                }
            }

        }

        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        sourceBuilder.query(queryBuilder);

        searchRequest.source(sourceBuilder);



        Map<String, Object> resMap = new HashMap<>();
        Long total = null;
        try {
            // 调用方法进行数据通信
            SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
            // 解析输出结果
            SearchHit[] hits = searchResponse.getHits().getHits();
            total = searchResponse.getHits().getTotalHits().value;
            List<SearchRepDto> searchResultList = new ArrayList<>();
            System.out.println("总数=========" + total);
            for (SearchHit hit : hits) {
                String id = hit.getId();
                String sourceAsString = hit.getSourceAsString();
                SearchRepDto searchResult = new SearchRepDto();
                System.out.println("结果：" + sourceAsString);

                String index_name = null;
                if (JSON.parseObject(sourceAsString).getString("caseTitle") != null) {
                    searchResult.setHighlightField(JSON.parseObject(sourceAsString).getString("caseTitle"));
                    index_name = "1";
                } else if (JSON.parseObject(sourceAsString).getString("contextTitle") != null) {
                    index_name = "2";
                    searchResult.setHighlightField(JSON.parseObject(sourceAsString).getString("contextTitle"));
                }
                searchResult.setId(id);
                searchResult.setType(index_name);
                searchResult.setSourceAsString(JSON.parseObject(sourceAsString));

                searchResultList.add(searchResult);
                resMap.put("searchResultList", searchResultList);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        resMap.put("total", total);
        return resMap;
    }
    /**
     * <p>新建文档</p>
     *
     * @param bean       要发送的文档 bean
     * @param index_name 索引名称 不能出现大写！！！
     * @return
     * @throws IOException
     */
    public RestStatus createDocument(Object bean, String index_name) throws IOException {

        GetIndexRequest getIndexRequest = new GetIndexRequest(index_name);
        boolean exit = client.indices().exists(getIndexRequest, RequestOptions.DEFAULT);

        if (!exit) {
            //1/1、创建索引请求
            CreateIndexRequest request = new CreateIndexRequest(index_name);
            //  1/2、客广端执行请求Indicesclient,请求后获得响应
            CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
            System.out.println("========>不存在创建" + createIndexResponse);
        }
        //创建请求
        IndexRequest request = new IndexRequest(index_name);
        request.timeout(TimeValue.timeValueSeconds(1));
        request.timeout("1s");
        //  我们的数据放入请求json将
        request.source(JSON.toJSONString(bean), XContentType.JSON);
//        客户端发送请求,获取响应的结果

        IndexResponse indexResponse = null;

        indexResponse = client.index(request, RequestOptions.DEFAULT);

        System.out.println(indexResponse.toString());//返回这行记录（doc）
        System.out.println(indexResponse.status());  //对应我们命令返回的状态CREATED
        return indexResponse.status();
    }


    /**
     * 删除文档
     */
    public RestStatus DeleteDocument(String id, String index_name) throws IOException {
        //Termsearch
        SearchRequest searchRequest = new SearchRequest(index_name);
        //构建搜索条件
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("columnId", id);
        sourceBuilder.query(termQueryBuilder);
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        searchRequest.source(sourceBuilder);
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        // 9.解析输出结果
        SearchHit[] hits = searchResponse.getHits().getHits();
        String es_Id=null;
        for (SearchHit hit : hits) {
            String sourceAsString = hit.getSourceAsString();
          es_Id  = JSON.parseObject(sourceAsString).getString("columnId");
        }
//        删除
        DeleteRequest request = new DeleteRequest(index_name, es_Id);
        DeleteResponse deleteResponse = client.delete( request, RequestOptions.DEFAULT);
        System.out.println(deleteResponse.status());
        System.out.println("删除索引成功");
        return  deleteResponse.status();
    }
}
